var root = "/stats/r/ts/"

var data = new Array();
var latest = null;


function showTooltip(x, y, contents) {
    $('<div id="tooltip">' + contents + '</div>').css( {
        position: 'absolute',
        display: 'none',
        top: y + 5,
        left: x + 5,
        border: '1px solid #fdd',
        padding: '2px',
        'background-color': '#fee',
        opacity: 0.80
    }).appendTo("body").fadeIn(200);
}


function viz(data, b, e) {
    
    $.plot($("#chart"), [data], {
	xaxis: { mode: "time", min: b, max: e },
	grid: { hoverable: true }
    });

    var previousPoint;
    $("#chart").bind("plothover", function (event, pos, item) {
        $("#x").text(pos.x.toFixed(2));
        $("#y").text(pos.y.toFixed(2));

        if (item) {
            if (previousPoint != item.dataIndex) {
                previousPoint = item.dataIndex;
                
                $("#tooltip").remove();
                var x = item.datapoint[0].toFixed(2),
                y = item.datapoint[1].toFixed(2);
                
                showTooltip(item.pageX, item.pageY, y);
            }
        }
        else {
            $("#tooltip").remove();
            previousPoint = null;            
        }
    });
};


function update_ci(b, e) {
    $("#ci").text("showing from [" + new Date(b).toUTCString() + "] to [" + new Date(e).toUTCString() + "]");
}


function main(item, k, ts, i) {
    var b, e;
    
    var x = function() {
	switch (i) {
	case "D":
	    b = new Date(e).addHours(-24);
	    break;
	case "W":
	    b = new Date(e).addDays(-7);
	    break;
	case "M":
	    b = new Date(e).addDays(-31);
	    break;
	case "N":
	    b = new Date(e).addDays(-90);
	    alert("TODO");
	    break;
	}
    };

    if (ts == 0) {
	var req =  root + item + "/" + k;
	$.getJSON(req, function(json) {
	    latest = json[0];
	    e = latest.ts_boundary;
	    x();
	    b = b.getTime();
	    viz(latest.values, b, e);
	    update_ci(b, e);
	});

    }

}


function show(item, k) {
    var ts;
    var i;

    var mr = $("#cc_mr :radio:checked").attr("value");
    if (mr == "a" || mr == null) {
	alert("TODO");
	return;
    } else {
	i = $("#cc_ms").attr("value");
	ts = 0;
	if ($("#cc_from :radio:checked").attr("value") == "cal") {
	    alert("TODO");
	}
    }

    main(item, k, ts, i);
}


function cc_r_s() {
    if ($("#cc_from :radio:checked").length == 0) {
	$("#cc_from :radio").attr("disabled", false);
	$("#cc_from :radio").first().attr("checked", "checked");
    }
}


function cc_r_a() {
    $("#cc_from :radio").removeAttr("checked").attr("disabled", true);
}
